using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
using System.IO;

public partial class TextureChannelTool : EditorWindow
{
    // 用于存储上次保存的路径和文件名
    private string lastSavePath = "";
    private string lastFileName = "TextureName";

    public enum OPTIONS
    {
        R = 0, G = 1, B = 2, A = 3,
        R_G2L = 4, G_G2L = 5, B_G2L = 6, A_G2L = 7,
        R_L2G = 8, G_L2G = 9, B_L2G = 10, A_L2G = 11,
        R_INV = 14, G_INV = 15, B_INV = 16, A_INV = 17,
        Black = 18, Write = 19,
    }

    [MenuItem("TA/工具/图层通道合并")]
    static void Init()
    {
        EditorWindow.GetWindow<TextureChannelTool>("图层通道合并工具").Show();
    }

    Texture2D[] editorArray = new Texture2D[4];
    OPTIONS[] types = new OPTIONS[] { OPTIONS.R, OPTIONS.R, OPTIONS.R, OPTIONS.R };
    int csvIndex = 1;
    int subIndex = 0;
    int toolBar = 0;
    bool isTGA = false;

    // 加载上次保存路径
    private void LoadLastSavePath()
    {
        lastSavePath = PlayerPrefs.GetString("TextureChannelTool_LastPath", "Assets");
        lastFileName = PlayerPrefs.GetString("TextureChannelTool_LastFileName", "TextureName");
    }

    // 更新上次保存路径
    private void UpdateLastSavePath(string savePath)
    {
        if (string.IsNullOrEmpty(savePath)) return;
        try
        {
            lastSavePath = Path.GetDirectoryName(savePath);
            lastFileName = Path.GetFileNameWithoutExtension(savePath);
            PlayerPrefs.SetString("TextureChannelTool_LastPath", lastSavePath);
            PlayerPrefs.SetString("TextureChannelTool_LastFileName", lastFileName);
            PlayerPrefs.Save();
        }
        catch (Exception e)
        {
            Debug.LogError("更新保存路径失败: " + e.Message);
        }
    }

    void OnGUI()
    {
        if (string.IsNullOrEmpty(lastSavePath))
        {
            LoadLastSavePath();
        }

        GUILayout.Label("R通道");
        editorArray[0] = (Texture2D)EditorGUILayout.ObjectField(editorArray[0], typeof(Texture2D));
        types[0] = (OPTIONS)EditorGUILayout.EnumPopup("来自通道:", types[0]);

        GUILayout.Label("G通道");
        editorArray[1] = (Texture2D)EditorGUILayout.ObjectField(editorArray[1], typeof(Texture2D));
        types[1] = (OPTIONS)EditorGUILayout.EnumPopup("来自通道:", types[1]);

        GUILayout.Label("B通道");
        editorArray[2] = (Texture2D)EditorGUILayout.ObjectField(editorArray[2], typeof(Texture2D));
        types[2] = (OPTIONS)EditorGUILayout.EnumPopup("来自通道:", types[2]);

        GUILayout.Label("A通道");
        editorArray[3] = (Texture2D)EditorGUILayout.ObjectField(editorArray[3], typeof(Texture2D));
        types[3] = (OPTIONS)EditorGUILayout.EnumPopup("来自通道:", types[3]);

        isTGA = EditorGUILayout.Toggle("tga", isTGA);

        if (GUILayout.Button("合成"))
        {
            Save();
        }

        if (GUILayout.Button("All"))
        {
            editorArray[3] = editorArray[2] = editorArray[1] = editorArray[0];
        }

        GUILayout.BeginHorizontal();
        if (GUILayout.Button("NormalBA"))
        {
            editorArray[3] = editorArray[2] = editorArray[1] = editorArray[0];
            types[0] = OPTIONS.B;
            types[1] = OPTIONS.A;
            types[2] = OPTIONS.Black;
            types[3] = OPTIONS.Write;
            Save();
        }

        if (GUILayout.Button("诛仙Mask"))
        {
            editorArray[3] = editorArray[2] = editorArray[1] = editorArray[0];
            types[0] = OPTIONS.R;
            types[1] = OPTIONS.Black;
            types[2] = OPTIONS.Black;
            types[3] = OPTIONS.G;
            Save();
        }
        GUILayout.EndHorizontal();

        if (GUILayout.Button("诛仙一键"))
        {
            string path = EditorUtility.SaveFolderPanel("", "", "");
            if (path.Length > 0)
            {
                path += "/";
                string rpath = "Assets" + path.Substring(Application.dataPath.Length);
                DirectoryInfo root = new DirectoryInfo(path);
                FileInfo[] files = root.GetFiles();

                for (int i = 0; i < files.Length; i++)
                {
                    var f = files[i];
                    if (f.Extension.ToLower() == ".obj")
                    {
                        string _path = rpath + f.Name;
                        string csv_path = _path.Substring(0, _path.Length - 3) + "csv";

                        if (File.Exists(csv_path))
                        {
                            AddUVToObject(_path, csv_path, csvIndex, subIndex);
                            AssetDatabase.ImportAsset(_path);
                            try { File.Delete(csv_path); }
                            catch (Exception e) { Debug.LogError(e.ToString()); }
                        }
                    }
                    else if (f.Extension.ToLower() == ".dds")
                    {
                        string _path = rpath + f.Name;
                        Texture2D t2d = AssetDatabase.LoadAssetAtPath<Texture2D>(_path);

                        // 生成法线贴图
                        editorArray[3] = editorArray[2] = editorArray[1] = editorArray[0] = t2d;
                        types[0] = OPTIONS.B;
                        types[1] = OPTIONS.A;
                        types[2] = OPTIONS.Black;
                        types[3] = OPTIONS.Write;
                        isTGA = true;
                        string normal_path = _path.Substring(0, _path.Length - 4) + "_N.tga";
                        CombineMesh(normal_path);
                        AssetDatabase.ImportAsset(normal_path);

                        // 生成遮罩贴图
                        types[0] = OPTIONS.R;
                        types[1] = OPTIONS.Black;
                        types[2] = OPTIONS.Black;
                        types[3] = OPTIONS.G;
                        string mask_path = _path.Substring(0, _path.Length - 4) + "_M.tga";
                        CombineMesh(mask_path);
                        AssetDatabase.ImportAsset(mask_path);

                        GameObject.DestroyImmediate(t2d, true);
                        try { File.Delete(_path); } catch (Exception e) { }
                    }
                }
                AssetDatabase.Refresh();
            }
        }
    }

    private void Save()
    {
        bool found = false;
        for (int i = 0; i < 4; i++)
        {
            if (editorArray[i] != null)
                found = true;
        }
        if (!found)
        {
            EditorUtility.DisplayDialog("提示", "没有图片被选择", "ok");
            return;
        }

        // 新增逻辑：当lastSavePath为空时，设置为第一张贴图的路径
        if (string.IsNullOrEmpty(lastSavePath) && editorArray[0] != null)
        {
            string firstTexturePath = AssetDatabase.GetAssetPath(editorArray[0]);
            if (!string.IsNullOrEmpty(firstTexturePath))
            {
                lastSavePath = Path.GetDirectoryName(firstTexturePath);
                lastFileName = Path.GetFileNameWithoutExtension(firstTexturePath);

                // 保存到PlayerPrefs
                PlayerPrefs.SetString("TextureChannelTool_LastPath", lastSavePath);
                PlayerPrefs.SetString("TextureChannelTool_LastFileName", lastFileName);
                PlayerPrefs.Save();
            }
        }
        string defaultPath = lastSavePath;
        string defaultName = lastFileName;

        if (isTGA)
        {
            string defaultFullPath = Path.Combine(defaultPath, defaultName + ".tga");
            string path = EditorUtility.SaveFilePanelInProject("Save Texture", defaultName, "tga",
                "请输入保存文件名", defaultFullPath);
            if (path.Length != 0)
            {
                CombineMesh(path);
                AssetDatabase.ImportAsset(path);
            }
        }
        else
        {
            string defaultFullPath = Path.Combine(defaultPath, defaultName + ".png");
            string path = EditorUtility.SaveFilePanelInProject("Save Texture", defaultName, "png",
                "请输入保存文件名", defaultFullPath);
            if (path.Length != 0)
            {
                CombineMesh2(path);
                AssetDatabase.ImportAsset(path);
            }
        }
    }

   
}